package priv.happy.mealpickpro.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import priv.happy.mealpickpro.domain.Barrage;
import priv.happy.mealpickpro.emum.SystemStatusCode;
import priv.happy.mealpickpro.service.BarrageService;
import priv.happy.mealpickpro.vo.ApiResponse;

import java.util.List;

/**
 * @Author: HAPPY
 * @Project_name: mealPickPro
 * @Package_name: priv.happy.mealpickpro.controller
 * @Date: 2023/10/23 22:27
 * @Description:
 */
@RestController
@RequestMapping("/api/v2/barrage")
public class BarrageController {

    @Autowired
    BarrageService barrageService;

    @GetMapping
    public ApiResponse<List<Barrage>> list() {
        ApiResponse<List<Barrage>> apiResponse = new ApiResponse<>();

        try {
            apiResponse.setData(barrageService.list(new QueryWrapper<Barrage>()
                            .orderByDesc("time")))
                    .setCode(SystemStatusCode.SUCCESS.getCode())
                    .setSuccess(true).setMessage("查询弹幕信息成功");
        } catch (Exception e) {
            apiResponse.setSuccess(false).setCode(SystemStatusCode.INTERNAL_SERVER_ERROR.getCode())
                    .setMessage("查询弹幕信息失败");
        }
        return apiResponse;
    }

    @PostMapping
    public ApiResponse<List<Barrage>> list(@RequestBody Barrage barrage) {
        ApiResponse<List<Barrage>> apiResponse = new ApiResponse<>();

        try {
            if (barrageService.save(barrage.setTime(DateUtil.now()))) {
                apiResponse.setSuccess(true).setMessage("添加弹幕信息成功")
                        .setData(barrageService.list()).setCode(SystemStatusCode.SUCCESS.getCode());
            } else {
                apiResponse.setSuccess(false).setCode(SystemStatusCode.INTERNAL_SERVER_ERROR.getCode())
                        .setMessage("添加弹幕信息失败");
            }
        } catch (Exception e) {
            apiResponse.setSuccess(false).setCode(SystemStatusCode.INTERNAL_SERVER_ERROR.getCode())
                    .setMessage("添加弹幕信息失败");
        }
        return apiResponse;
    }
}
